package com.simemg.reader.provider;

import com.simemg.reader.ResourceTable;
import com.simemg.reader.store.Book;
import com.simemg.reader.utils.RequestUtil;
import ohos.agp.components.*;
import ohos.app.Context;
import java.util.List;
import java.util.Optional;

public class BookListProvider extends BaseItemProvider {
    private final List<Book> bookList;
    private final Context context;

    public BookListProvider(List<Book> bookList, Context context) {
        this.bookList = bookList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return bookList == null ? 0 : bookList.size();
    }

    @Override
    public Object getItem(int i) {
        return  Optional.of(this.bookList.get(i));
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_component_book, null, false);
        if (!(component instanceof ComponentContainer)) {
            return null;
        }
        if (bookList.get(i).getName() != null) {
            Text name = (Text)component.findComponentById(ResourceTable.Id_name);
            name.setText(bookList.get(i).getName());
        }
        if (bookList.get(i).getImg() != null) {
            Image image = (Image) component.findComponentById(ResourceTable.Id_img);
            RequestUtil.LoadImg(bookList.get(i).getImg()).setContext(context).setImage(image).execute();
        }
        if (bookList.get(i).getAuthor() != null){
            Text author = (Text) component.findComponentById(ResourceTable.Id_author);
            author.setText(bookList.get(i).getAuthor());
        }
        if (bookList.get(i).getInfo() != null) {
            Text info = (Text) component.findComponentById(ResourceTable.Id_info);
            info.setText(bookList.get(i).getInfo());
        }
        if (bookList.get(i).getLastPage() != null) {
            Text lastPage = (Text) component.findComponentById(ResourceTable.Id_last_page);
            lastPage.setText(bookList.get(i).getLastPage());
        }
        return component;
    }



}
